package com.open.capacity.finance.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.open.capacity.finance.entity.SourceBaseBudgetExcute;
import com.open.capacity.finance.entity.SourceBaseUsecar;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.model.SysDepartment;
import com.open.capacity.user.service.SysCompanyService;
import com.open.capacity.user.service.SysDepartmentService;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.KeyValue;
import org.apache.commons.collections4.keyvalue.DefaultKeyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.finance.entity.SourceBaseAsset;
import com.open.capacity.finance.dao.SourceBaseAssetDao;
import com.open.capacity.finance.service.SourceBaseAssetService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class SourceBaseAssetServiceImpl implements SourceBaseAssetService {

    @Autowired
    private SourceBaseAssetDao sourceBaseAssetDao;

    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private SysDepartmentService departmentService;

    /**
     * 保存到数据库
     *
     * @param url
     */
    @Transactional
    public int save2db(String companyId, Integer kjnd, Integer importway, String url) {
        MultipartFile multipartFile = FileUtil.toMultipartFile("assetdataXls", url);
        ImportParams params = new ImportParams();
        params.setTitleRows(0); //前面header空几行
        params.setHeadRows(1);
        params.setStartRows(1);
        // 开启excel校验
        params.setNeedVerify(false);

        List<SourceBaseAsset> list = new ArrayList<>();
        try {
            list = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                    SourceBaseAsset.class, params);
        } catch (Exception e) {
            log.error("从文件读取数据错误:{}", e.getMessage());
        }

        SysCompany company = companyService.findById(companyId);
        List<SysDepartment> departments = departmentService.findDepartments(new HashMap<>());

        //删除旧数据
        if (importway == 1) {
            delete(companyId);
        }

        int _t = 1;
        for (SourceBaseAsset item : list) {
            if (StringUtil.isEmpty(item.getAssetName()) || item.getAssetName().equals("——")) {
                continue;
            }
            item.setCompanyId(companyId);
            item.setCompanyName(company.getFullName());
            _t = item.getCategoryName().indexOf("]") > 0 ? item.getCategoryName().indexOf("]") : 1;
            item.setCategoryCode(item.getCategoryName().substring(1, _t).replace("[", "").replaceAll("]", ""));
            if (item.getOrigValue() == null) {
                item.setOrigValue(BigDecimal.ZERO);
            }
            Optional<SysDepartment> first = departments.stream().filter(t -> t.getName().equals(item.getDepartmentName())).findFirst();
            if (first.isPresent()) {
                item.setDepartmentId(first.get().getId());
            }
            sourceBaseAssetDao.save(item);
        }

        return list.size();
    }



    /**
     * 删除
     *
     * @param companyId
     */
    public int delete(String companyId) {
        return sourceBaseAssetDao.deleteByCompanyId(companyId);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SourceBaseAsset findById(String id) {
        return sourceBaseAssetDao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<SourceBaseAsset> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SourceBaseAsset> list = sourceBaseAssetDao.findAll(params);
        PageInfo<SourceBaseAsset> pageInfo = new PageInfo(list);

        return PageResult.<SourceBaseAsset>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SourceBaseAsset> findAll(Map<String, Object> params) {
        return sourceBaseAssetDao.findAll(params);
    }

    @Override
    public List<SourceBaseAsset> findUseways(Map<String, Object> params) {
        return sourceBaseAssetDao.getCarUsewayData(params);
    }
}
